package com.itheima.mp.controller;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itheima.mp.domain.po.OrderDetailItem;
import com.itheima.mp.domain.po.OrdersMpapi;

import com.itheima.mp.mapper.OrdersMpapiMapper;
import com.itheima.mp.service.IOrdersMpapiService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-12-03
 */
@RestController
@RequestMapping("/orders-mpapi")
public class OrdersMpapiController {
    @Autowired
    private IOrdersMpapiService ordersMpapiService;

    // GET 请求 - 获取所有订单
    @GetMapping
    public List<OrdersMpapi> getAllOrders() {
        val list = ordersMpapiService.list();
        list.forEach(ordersMpapi -> {
            ordersMpapi.setOrderDetailItems();
        });
        return list;
    }

    // GET 请求 - 根据 ID 获取订单
    @GetMapping("/{id}")
    public OrdersMpapi getOrderById(@PathVariable String id) {
        val byId = ordersMpapiService.getById(id);
        byId.setOrderDetailItems();
        return byId;
    }

    // POST 请求 - 创建新订单
    @PostMapping
    public boolean createOrder(@RequestBody OrdersMpapi ordersMpapi) {
        try {
            return ordersMpapiService.save(ordersMpapi);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // POST 请求 - 更新订单详情
    @PostMapping("/updateDetails/{id}")
    public boolean updateOrderDetails(@PathVariable String id, @RequestBody List<OrderDetailItem> items) {
        OrdersMpapi order = new OrdersMpapi();
        order.setOrderId(id);
        try {
            order.setOrderDetailsFromList(items);
            return ordersMpapiService.updateById(order);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


}
